var baseurl = '';
var smallImgArg = '?x-oss-process=style/goods_img_3';
var smallImgArg300 = '?x-oss-process=style/goods_img_2';
var smallImgArg200 = '?x-oss-process=style/goods_img';


function check_support_webp() {
    var isSupportWebp = document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') == 0;
    return isSupportWebp
}



if( check_support_webp()  ) {
    smallImgArg = '?x-oss-process=style/goods_webp_3';
    smallImgArg300 = '?x-oss-process=style/goods_webp_2';
    smallImgArg200 = '?x-oss-process=style/goods_webp';
}

define(function(require,exports,module) {
    var _this = this;
    //yx
    //var httpImageUrl="https://fm95338bucket.oss-cn-shenzhen.aliyuncs.com/";
    //zs
    //var httpImageUrl="https://sfddj-img-bucket.oss-cn-shenzhen.aliyuncs.com/";
    var httpImageUrl;
    var myDoMain = '';
    if(window.location.host == 'm.sfddj.com' || window.location.host == '120.76.47.184' || window.location.host == '120.76.207.85' || window.location.host == '120.76.44.28') {
        // httpImageUrl="https://sfddj-img-bucket.oss-cn-shenzhen.aliyuncs.com/";
        httpImageUrl = "https://img.sfddj.com/";
        myDoMain = "https://m.sfddj.com";
    }
    else if (window.location.host == 'hdm.sfddj.com') {
        httpImageUrl = "https://img.sfddj.com/";
        myDoMain = 'https://hdm.sfddj.com';
    }
    else if (window.location.host == 'itsm.sfddj.com') {
        // httpImageUrl="https://fm95338bucket.oss-cn-shenzhen.aliyuncs.com/";
        httpImageUrl = "https://img.fx-sf.com/";
        myDoMain = 'https://itsm.sfddj.com';
    }
    else if (window.location.host == 'shop.fx-sf.com') {
        // httpImageUrl="https://fm95338bucket.oss-cn-shenzhen.aliyuncs.com/";
        httpImageUrl = "https://img.fx-sf.com/";
        myDoMain = 'https://shop.fx-sf.com';
    }
    else if(window.location.host == 'www.shhyxypsx.com') {
        httpImageUrl = "https://img.fx-sf.com/";
        myDoMain = 'https://www.shhyxypsx.com';
    }
    else if(window.location.hostname == 'localhost') {
        httpImageUrl = "http://img-dev.sfddj.com/";
        myDoMain = 'http://localhost:8082';
    }
    exports.httpImageUrl = httpImageUrl;
    exports.myDoMain = myDoMain;
    //加入购物车的动画
    function AddCarAnimate(_X,_Y,target,sLeft,sTop,offsetDis,callBack) {
        // var _X = e.gesture.center.x;
        // var _Y = e.gesture.center.y;
        var time = null;
        var timeTwo = null;
        target.removeClass('myRotateFast');
        target.css({ 'left':_X,'top':_Y, 'opacity':1});
        clearTimeout(time);
        time = setTimeout(function() {
            target.addClass('myRotateFast').stop().animate({'left':_X,'top':_Y-50, 'opacity':1},300,function() {
                target.stop().animate({'left':sLeft,'top':sTop},600,function() {
                    target.removeClass('myRotateFast');
                    clearTimeout(timeTwo);
                    timeTwo = setTimeout(function() {
                        target.stop().animate({'top':sTop + offsetDis*2, 'opacity':0},200,function() {
                            if(callBack) callBack();
                        })
                    },200)
                });
            });

        },30);
        // HamstopPropaga();
        // e.stopPropagation();
        // e.preventDefault()
    }
    exports.AddCarAnimate = AddCarAnimate;

    // hammer 冒泡
    function HamstopPropaga() {
        window.event.returnValue = false;
        return false;
    }
    exports.HamstopPropaga = HamstopPropaga;

    //hammer事件
    function HammerEvent(obj) {
        this.obj = obj;
    }

    HammerEvent.prototype.addHamEvent = function(obj,type,fn) {
        this.obj = new Hammer.Manager(obj);
        this.obj.add(new Hammer.Pan({velocity: 0,threshold: 120, direction:Hammer.DIRECTION_ALL}) ); //平滑
        this.obj.add(new Hammer.Swipe({threshold:8, direction:Hammer.DIRECTION_ALL}));
        this.obj.add(new Hammer.Tap({}));
        this.obj.add(new Hammer.Press({velocity:0.6,threshold:8})); //长时间下压
        this.obj.off(type);
        this.obj.on(type,function(e) {
            if(fn) fn(e);
            //e.preventDefault();
            //e.stopPropagation();
        });
    };

    exports.HammerEvent = HammerEvent;


    /* 数字验证 */
    function ValiNum(obj,fn1,fn2) {
        var reg = new RegExp("^[0-9]*$");
        if(!reg.test(obj.val())){
            if(fn1) fn1();
        }
        else if( obj.val() <= 0) {
            // TipLayer("数量不能小余1");
            obj.val(1);
        }
        else{if(fn2) fn2();}
    }
    exports.ValiNum = ValiNum;

    /* 字数统计 */
    function statInputNum(textArea,numItem) {
        var max = [];
        var curLength = [];
        textArea.each(function(i) {
            max[i] = parseInt(numItem.eq(i).text());

            if(textArea.eq(i).val().length > 0) {
                curLength[i] = textArea.eq(i).val().length;
                numItem.eq(i).empty().text(max[i] - curLength[i]);
            }
            textArea.eq(i).attr("maxlength", max[i]).on('input propertychange', function () {
                curLength[i] = $(this).val().length;
                numItem.eq(i).empty().text(max[i] - curLength[i]);
            });
        });

    }
    exports.statInputNum = statInputNum;


    /* 购物车价格统计 */
    function ShopSumPrice(obj,tarFather,target,sumPrice) {
        var _price = 0;
        obj.each(function(i) {
            if(obj.eq(i).hasClass('active')) {
                var _oGoodsPrice = obj.eq(i).parents(tarFather).find(target);
                _oGoodsPrice.each(function(i) {
                    _price += (_oGoodsPrice.eq(i).text())*1;
                    return  _price;
                });
            }

        });
        sumPrice.text(_price.toFixed(2));
    }
    exports.ShopSumPrice = ShopSumPrice;


    /*************** 弹框效果 s***************/

    //提示框
    function TipLayer (sCont,sStyle,fn,T) {
        layer.open({
            content: sCont,
            style:sStyle != 'no' ? sStyle : 'background-color:rgba(255,255,255,1); color:#252525; border:none; border-radius: 5px;',
            scrollbar: false,
            time: T || 2,
            shadeClose: false,
            success:function() {if(fn)fn();}
        });
        NoTouchMove($('.laymshade'))
    }
    exports.TipLayer = TipLayer;

    //提示框_没有遮罩层
    function TipLayer_noShade (sCont,sStyle,fn, T) {
        layer.open({
            content: sCont,
            style:sStyle != 'no' ? sStyle : 'background-color:rgba(255,255,255,1); color:#252525; border:none; border-radius: 5px;',
            scrollbar: false,
            time: T || 2,
            shade:false,
            shadeClose: false,
            success:function() {if(fn)fn();}
        });
        NoTouchMove($('.laymshade'))
    }
    exports.TipLayer_noShade = TipLayer_noShade;

    //框消失后执行回调提示框
    function TipLayerEnd (sCont,sStyle,fn,T) {
        layer.open({
            content: sCont,
            style:sStyle != 'no' ? sStyle : 'background-color:rgba(255,255,255,1); color:#252525; border:none; border-radius: 5px;',
            scrollbar: false,
            time: T || 2,
            shadeClose: false,
            end:function() {if(fn)fn();}
        });
        NoTouchMove($('.laymshade'))
    }
    exports.TipLayerEnd = TipLayerEnd;

    // 用户手动关闭弹框
    function TipLayerLong (sCont,sStyle) {
        layer.open({
            content: sCont,
            style:sStyle != 'no' ? sStyle : 'background-color:rgba(255,255,255,1); color:#252525; border:none; border-radius: 5px;',
            scrollbar: false,
            shadeClose: true
        });
        NoTouchMove($('.laymshade'))
    }
    exports.TipLayerLong = TipLayerLong;

    // 用户手动关闭弹框有关闭按钮
    function TipLayerLongClose (sTit, sCont, sStyle, fn) {
        layer.open({
            title: sTit != 'no' ? sTit : '',
            content: sCont,
            style:sStyle != 'no' ? sStyle : 'background-color:rgba(255,255,255,1); color:#252525; border:none; border-radius: 5px;',
            scrollbar: false,
            shadeClose: true,
            closeBtn:1,
            success:function() {if(fn)fn();}
        });
        NoTouchMove($('.laymshade'))
    }
    exports.TipLayerLongClose = TipLayerLongClose;


    //带按钮提示框
    function TipBtnLayer (sCont,sTit,btnName,yesFn,cancelFn,fn) {
        layer.open({
            title: sTit != 'no' ? sTit : '',
            content: sCont,
            btn: btnName == undefined ? ['确定'] : [btnName],
            shadeClose: false,
            scrollbar: false,
            yes:function() {if(yesFn) yesFn(); LayerCloseAll();},
            cancel:function() {if(cancelFn) cancelFn();},
            success:function() {
                if(fn)fn();
                $('.layermbtn span').css({'width': '100%'})
            }
        });
        NoTouchMove($('.laymshade'))
    }
    exports.TipBtnLayer = TipBtnLayer;

    // 标题提示框
    function TipTitleLayer (sTitle,styleTit,sCont,fn) {
        layer.open({
            title: [ sTitle,'background-color:#fff; color:#666; font-weight:bold' ],
            content: sCont,
            shadeClose:false,
            scrollbar: false,
            style: styleTit,
            cancel:function() {if(fn) fn();}

        });
        NoTouchMove($('.laymshade'))
    }
    exports.TipTitleLayer = TipTitleLayer;

    //询问层
    function askLayer(sCont,yesFn, noFn,sTit,callBack, aBtnName) {
        layer.open({
            //no 为没有标题 sTit为设置标题
            title:sTit != 'no' ? sTit : '',
            content: sCont,
            btn: aBtnName == undefined ? ['确认', '取消'] : aBtnName,
            shadeClose: false,
            scrollbar: false,
            yes: yesFn,
            no: noFn,
            cancel:noFn,
            success:function() {
                if(callBack) callBack();
            }

        });
        NoTouchMove($('.laymshade'))
    }
    exports.askLayer = askLayer;

    // 关闭所有弹框
    function LayerCloseAll() {
        layer.closeAll();
    }
    exports.LayerCloseAll = LayerCloseAll;

    //加载层
    function loadLayer(cont) {
        layer.open({type: 2,content:cont,shadeClose: false,});
        NoTouchMove($('.laymshade'))
    }
    exports.loadLayer = loadLayer;


    //防止滑动
    function NoTouchMove (obj) {
        obj.on('touchmove',function() {return false;})
    }
    exports.NoTouchMove = NoTouchMove;


    /*************** 弹框效果 e***************/

    //节流控制
    function throttle(method, context,time) {
        time == undefined ? time = 200 : time = time;
        //console.log(time)
        clearTimeout(method.tId);
        method.tId = setTimeout(function () {
            method.call(context);
            //console.log(111)
        }, time);
    }
    exports.throttle = throttle;



    //s20是代表20秒 h是指小时，如12小时则是：h12 d是天数，30天则：d30
    //写cookies setCookie("name","hayden",'s20');
    function setCookie(name,value,time) {
        var strsec;
        if (time == undefined) {
            var Days = 30; //默认30天有效期
            strsec = Days*24*60*60*1000;
        }
        else {
            strsec = getsec(time)*1;
        }
        var exp = new Date();
        exp.setTime(exp.getTime() + strsec);
        document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString() + ";path=/";
    }
    exports.setCookie = setCookie;

    //读取cookies getCookie("name")
    function getCookie(name) {
        var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
        if(arr=document.cookie.match(reg)) {
            return unescape(arr[2]);
        }
        else{
            return null;
        }

    }
    exports.getCookie = getCookie;

    //删除cookies delCookie('name')
    function delCookie(name) {
        var exp = new Date();
        exp.setTime(exp.getTime() - 1);
        var cval=getCookie(name);
        if(cval!=null)
            document.cookie = name + "="+cval+";expires="+exp.toGMTString() + ";path=/";
    }
    exports.delCookie = delCookie;

    //设置cookie时间
    function getsec(str) {
        var str1=str.substring(1,str.length)*1;
        var str2=str.substring(0,1);
        if (str2=="s") {
            return str1*1000;
        }
        else if (str2=="h") {
            return str1*60*60*1000;
        }
        else if (str2=="d") {
            return str1*24*60*60*1000;
        }
    }

    /* 验证码倒计时 */
    function CutTime(time,fn1,fn2) {
        var _AllTime = time;
        var _T = null;
        clearInterval(_T);
        _T = setInterval(function() {
            if(time<=0) {
                clearInterval(_T);
                if(fn1)fn1(_AllTime);
            }
            else {
                time--;
                if(fn2)fn2(time);
            }
        },1000)
    }
    exports.CutTime = CutTime;

    /*手机号码验证*/
    function checkMobile(obj,fn1,fn2,fn3){
        var oIphone = obj.val();
        var reg = /^(1[1|2|3|4|5|6|7|8|9])[\d]{9}$/;   //验证手机号码

        if(oIphone == '') {
            if(fn1)fn1()
        }
        else if (!reg.test(oIphone) ){

            if(fn2)fn2();
        }
        else {
            if(fn3)fn3();
        }
    }
    exports.checkMobile = checkMobile;


    /*密码验证*/
    function checkPassWord(obj,fn1,fn2,fn3){
        var _val = obj.val();
        var reg = /^[a-zA-Z0-9]{6,20}$/;   //6-20位数字和英文

        if(_val == '') {
            if(fn1)fn1()
        }
        else if (!reg.test(_val) ){
            if(fn2)fn2();
        }
        else {
            if(fn3)fn3();
        }
    }
    exports.checkPassWord = checkPassWord;




    /*用户名验证*/
    function checkUserName(obj,fn1,fn2,fn3){
        var _userName = obj.val();
        var reg = /^[A-Za-z\u4e00-\u9fa5][A-Za-z0-9\u4e00-\u9fa5]{1,9}$/;   //验证用户名

        if(_userName == '') {
            if(fn1)fn1()
        }
        else if (!reg.test(_userName) ){

            if(fn2)fn2();
        }
        else {
            if(fn3)fn3();
        }
    }

    exports.checkUserName = checkUserName;



    //图片预加载(window)
    function lazLoadingImgEcho(obj,fn) {
        echo.init({
            container:obj,
            offset : 300,
            throttle : 50, //设置图片延迟加载的时间
            callback: function (element, op) {
                if(fn)fn(element, op)
                // console.log(element, 'has been', op + 'ed')
                var $el = $(element);
                var sUl = $el.attr('src');
                loadImageCheck(sUl, function () {
                    $el.addClass('fadeIn');
                    $el = null;
                });
            }
        });
    }
    exports.lazLoadingImgEcho = lazLoadingImgEcho;

    function lazLoadingImg(obj) {
        this.obj = obj;
    }

    //添加图片预加载
    lazLoadingImg.prototype.AddLazLoadingImg = function (obj, fn) {
        this.obj = echoChangeByCc.initNew({
            container:obj,
            unload:false,
            offset : 300,
            throttle : 80, //设置图片延迟加载的时间
            callback: function (element, op) {
                var $el = $(element);
                var sUl = $el.attr('src');
                loadImageCheck(sUl, function () {
                    $el.addClass('fadeIn');
                    $el = null;
                });
                if(fn) fn();
            }
        });
    };

    // 图片预加载 销毁
    lazLoadingImg.prototype.DestroyLazLoadingImg = function () {
        var _this = this.obj;
        if(_this && _this.detach) {
            _this.detach();
        }

    }


    // 图片预加载 刷新
    lazLoadingImg.prototype.RushLazLoadingImg = function () {
        var _this = this.obj;
        _this.render();
    }

    function loadImageCheck(url, callback) {
        //创建一个Image对象，实现图片的预下载
        var img = new Image();
        img.src = url;
        // 如果图片已经存在于浏览器缓存，直接调用回调函数
        if(img.complete) {
            callback();
            img = null;
            return; // 直接返回，不用再处理onload事件
        }
        img.onload = function () {
            //图片下载完毕时异步调用callback函数。
            callback();
            img = null;
        };
    }

    exports.lazLoadingImg = lazLoadingImg;

    function lazLoadingImgEchoAbs(obj,fn) {
        echoChangeByCc.initNew({
            container:obj,
            unload:false,
            offset : 200,
            throttle : 30, //设置图片延迟加载的时间
            callback: function (element, op) {
                var $el = $(element);
                // console.log($el)
                var sUl = $el.attr('src');
                loadImageCheck(sUl, function () {
                    $el.addClass('fadeIn');
                    $el = null;
                });
                if(fn) fn();
            }
        });
    }
    exports.lazLoadingImgEchoAbs = lazLoadingImgEchoAbs;



    //mui插件事件开关
    function OffMuiEvent(arg) {
        mui.init({
            gestureConfig:{
                tap: arg, 	//默认为true
                swipe: arg, //默认为true
            }
        });
    }
    exports.OffMuiEvent = OffMuiEvent;



    //设置li图片高度 父级获取
    function SetImgHeight(obj, getWidth) {
        var htmlFontSize = $('html').css('font-size');
        var intSize = htmlFontSize.split('p')[0];
        var imgWidth = null;

        if (obj[0].nodeName.toLowerCase() === 'li') {
            getWidth ? imgWidth = getWidth/intSize : imgWidth = obj.find('figure').eq(0).parents('a').width()/intSize;
            // obj.find('figure:not(:first)').css({'height': imgWidth+'rem', 'width': imgWidth+'rem'});
            obj.find('figure').css({'height': imgWidth+'rem', 'width': imgWidth+'rem'});
        }
        else {
            getWidth ? imgWidth = getWidth/intSize : imgWidth = obj.find('li figure').eq(0).parents('a').width()/intSize;
            // obj.find('li figure:not(:first)').css({'height': imgWidth+'rem', 'width': imgWidth+'rem'});
            obj.find('li figure').css({'height': imgWidth+'rem', 'width': imgWidth+'rem'});
        }
    }
    exports.SetImgHeight = SetImgHeight;


    // 日期 2015-09-01 11:16:00
    function FormatDateTime (date, minType, point) {
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? ('0' + m) : m;
        var d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        var h = date.getHours();
        h = h < 10 ? ('0' + h) : h;
        var minute = date.getMinutes();
        minute = minute < 10 ? ('0' + minute) : minute;
        var seconds = date.getSeconds();
        seconds = seconds < 10 ? ('0' + seconds) : seconds;
        var _sep ='-';
        if(point) _sep = point;

        // 最小到天
        if(minType == 'minDay') {
            return y + _sep + m + _sep + d
        }
        // 最小到分钟
        else if (minType == 'minMinute') {
            return y + _sep + m + _sep + d + ' '+ h + ':' + minute
        }
        // 最小到秒
        else {
            return y + _sep + m + _sep + d + ' ' + h + ':' + minute + ':' + seconds;
        }
    }

    exports.FormatDateTime = FormatDateTime;

    /*************** 滚动条效果 s***************/
    function ScrollBar(obj) {
        this.obj = obj;
    }

    //添加滚动条
    ScrollBar.prototype.AddScroll = function (obj,sOptions) {
        this.obj = new JRoll(obj,sOptions);
    };

    //刷新滚动条
    ScrollBar.prototype.ReScroll = function (fn) {
        var _this = this.obj;
        _this.refresh();
        if(fn)fn();
    };

    //删除滚动条
    ScrollBar.prototype.DelScroll = function (fn) {
        var _this = this.obj;
        _this.destroy();
        if(fn)fn();
    };

    //滚动 到 0
    ScrollBar.prototype.ScrollTo = function (x,y,time,fn) {
        var _this = this.obj;
        _this.scrollTo(x,y,time, false, function () {
            if(fn)fn(_this)
        });

    };

    //滚动开始事件
    ScrollBar.prototype.ScrollStart = function (fn) {
        var _this = this.obj;
        _this.on('scrollStart', fn);
    };

    //滚动结束事件
    ScrollBar.prototype.ScrollEnd = function (fn1,fn2) {
        var _this = this.obj;
        _this.on('scrollEnd', fn1);
        if(fn2)fn2()
    };

    //滚动监听
    ScrollBar.prototype.ScrollIng = function (fn) {
        var _this = this.obj;
        //this.obj.on('scroll', fn);
        this.obj.on('scroll', function() {
            if(fn)fn(_this)
        });

    };

    //滚动下拉刷新
    ScrollBar.prototype.ScrollPullDown = function (sOptions) {
        var _this = this.obj;
        _this.pulldown(sOptions);

    };

    exports.ScrollBar = ScrollBar;


    function getFontSize(){
        var doc = document,win = window;
        var docEl = doc.documentElement,
            resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
            recalc = function () {
                var clientWidth = docEl.clientWidth;
                if (!clientWidth) return;
                //如果屏幕大于750（750是根据我效果图设置的，具体数值参考效果图），就设置clientWidth=750，防止font-size会超过100px
                if(clientWidth > 750){clientWidth=750}
                //设置根元素font-size大小
                docEl.style.fontSize = 100 * (clientWidth / 750) + 'px';
            };
        //屏幕大小改变，或者横竖屏切换时，触发函数
        win.addEventListener(resizeEvt, recalc, false);
        //文档加载完成时，触发函数
        // doc.addEventListener('DOMContentLoaded', recalc, false);
        $(doc).ready(function() { recalc(); });


    }

    exports.getFontSize = getFontSize;

    function getGoodsNo(url) {
        var  reg = new RegExp("^YW[a-zA-Z0-9]{12,14}$");
        var aUrl = '';
        if(!url) return;
        if(url.indexOf('/') > -1) {
            aUrl = url.substr(0).split('/');
            for(var i=0; i<aUrl.length; i++) {
                if( checkField(aUrl[i]) ) {
                    return checkField(aUrl[i])
                }
                else if( checkField(aUrl[i]) == undefined ) {
                    return false;
                }
            }
        }
        else {
            if( checkField(url) ) {
                return checkField(url);
            }
            else if( checkField(url) == undefined ) {
                return false;
            }
        }

        function checkField(_url) {
            var _aUrl = '';
            if(_url.length >= 14) {
                if( _url.indexOf('?') > 0 ) {
                    _aUrl = _url.split('?');
                    for(var i=0; i<_aUrl.length; i++) {
                        if( reg.test(_aUrl[i]) ) {
                            return _aUrl[i];
                        }
                    }
                }
                else {
                    if( reg.test(_url) ) {
                        return _url;
                    }
                    else {
                        return false;
                    }
                }
            }
            else {
                return false;
            }
        }
    }

    exports.getGoodsNo = getGoodsNo;


    // 检测 安卓 ios 分享 大当家 链接跳转
    function  JudgeAppHref(obj) {
        var _href = '';
        var _Num = 0;
        var u = navigator.userAgent;
        //var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
        var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
        // 返回首页操作
        var hrefToHome = ['/', 'sf://'];
        var hrefName = ['/h/goodspay/goodsView/', 'sf://goodsDetail?goodsSn='];
        var sLocationArg = window.location.search.split('?')[1];
        var fxBtn = false;
        if(sLocationArg !== undefined ) {
            if(sLocationArg.search('sell_member_id') >-1) {
                fxBtn = true
            }
        }
        // console.log('我进来检测了')
        // 检测室安卓还是ios
        if(u.search('origin/sfddjapp') > 0) {
            if(isIOS) {
                _Num = 1;
                obj.each(function(i) {
                    _href = obj.eq(i).attr('_href');
                    // 检测回到首页
                    if(_href === 'home') {
                        obj.eq(i).attr('href', hrefToHome[_Num] + _href )
                    }
                    else {
                        if( getGoodsNo(_href) ) {
                            obj.eq(i).attr('href', hrefName[_Num] + getGoodsNo(_href));
                        }
                        // else if(){}
                        else {
                            obj.eq(i).attr('href', _href);
                        }
                    }

                })
            }
            else {
                obj.each(function(i) {
                    // 检测回到首页
                    _href = obj.eq(i).attr('_href');
                    if(_href === 'home') {
                        AndroidReHome(obj.eq(i));
                    }
                    else {
                        if( getGoodsNo(_href) ) {
                            //要去掉a标签自带的href属性，因为这个跳转比点击事件要快，如果有这个属性在安卓上会跳转两次
                            obj.eq(i).removeAttr('href');
                            AndroidGoods(obj.eq(i), getGoodsNo(_href))

                        }
                        else {
                            obj.eq(i).attr('href', _href)
                        }
                    }
                })
            }
        }

        //检测是否是微信小程序的环境
        else if( window.__wxjs_environment === 'miniprogram' ){
            obj.each(function (i) {
                // 如果有_href 这个自定义属性，_href 只有等于 home 或者 商品编号，就回到小程序页面；
                _href = obj.eq(i).attr('_href');

                if (_href) {
                    // 禁用掉 href
                    // obj.eq(i).attr("href", "javascript:void(0);");
                    obj.eq(i).removeAttr('href');
                    // 检测回到首页
                    if( _href === 'home' ) {
                        minAppEven(obj.eq(i));
                    }
                    else {
                        if( getGoodsNo(_href) ) {
                            minAppEven(obj.eq(i), getGoodsNo(_href));
                        }
                        else if(isDrawCouponLink(_href)){
                            minAppEven(obj.eq(i), false, '/pages/subPackages/home/drawCoupon/drawCoupon?ruleSign=' + isDrawCouponLink(_href))
                        }
                        else {
                            obj.eq(i).attr('href', _href)
                        }
                    }
                }

            })
        }

        else if( navigator.userAgent.indexOf('AlipayClient') > -1 && loadAliJs) {

            // seriesLoadScripts(['https://appx/web-view.min.js'], function(){

                // 判断是否运行在小程序环境里
                my.getEnv(function(res) {
                    // console.log(res.miniprogram) // true
                    if(res.miniprogram) {
                        obj.each(function (i) {
                            // 如果有_href 这个自定义属性，_href 只有等于 home 或者 商品编号，就回到小程序页面；
                            _href = obj.eq(i).attr('_href');

                            if (_href) {
                                // 禁用掉 href
                                // obj.eq(i).attr("href", "javascript:void(0);");
                                obj.eq(i).removeAttr('href');
                                // 检测回到首页
                                if( _href === 'home' ) {
                                    minAppEven(obj.eq(i),'','',true);
                                }
                                else {
                                    if( getGoodsNo(_href) ) {
                                        minAppEven(obj.eq(i), getGoodsNo(_href),'',true);
                                    }
                                    else {
                                        obj.eq(i).attr('href', _href)
                                    }
                                }
                            }

                        })
                    }
                    else {
                        _Num = 0;
                        obj.each(function(i) {
                            _href = obj.eq(i).attr('_href');
                            var appendData = _href.indexOf('?') > -1 ? "?" + _href.split('?')[1] : '';
                            if(_href === 'home') {
                                obj.eq(i).attr('href', hrefToHome[_Num] + _href)
                            }
                            else {
                                if( getGoodsNo(_href) ) {
                                    obj.eq(i).attr('href', hrefName[_Num] + getGoodsNo(_href) + appendData)
                                }
                                else {
                                    obj.eq(i).attr('href', _href)
                                }
                            }
                        })
                    }
                });
            // })

        }

        // 检测分享版本
        else if(fxBtn) {
            _Num = 0;
            obj.each(function(i) {
                _href = obj.eq(i).attr('_href');
                if(_href === 'home') {
                    obj.eq(i).attr('href',hrefToHome[_Num] + _href )
                }
                else {
                    if( getGoodsNo(_href) ) {
                        obj.eq(i).attr('href',hrefName[_Num] + getGoodsNo(_href) + '?' + sLocationArg )
                    }
                    else {
                        obj.eq(i).attr('href', _href + '?' + sLocationArg )
                    }
                }
            })
        }

        // 检测ddj
        else {
            _Num = 0;
            obj.each(function(i) {
                _href = obj.eq(i).attr('_href');
                var appendData = _href.indexOf('?') > -1 ? "?" + _href.split('?')[1] : '';
                if(_href === 'home') {
                    obj.eq(i).attr('href', hrefToHome[_Num] + _href)
                }
                else {
                    if( getGoodsNo(_href) ) {
                        obj.eq(i).attr('href', hrefName[_Num] + getGoodsNo(_href) + appendData)
                    }
                    else {
                        obj.eq(i).attr('href', _href)
                    }
                }
            })
        }

    }

    exports.JudgeAppHref = JudgeAppHref;
    //判断是否是h5的领券页
    function isDrawCouponLink(url) {
        // var  reg = new RegExp("^YW[a-zA-Z0-9]{12,14}$");
        var ruleSignStr = '';
        if(!url) return false;
        if(url.indexOf('/coupon/drawCoupon') > -1) {
            ruleSignStr = url.split('ruleSign=')[1];
            if(ruleSignStr.indexOf('&') > -1){
                var ruleSign = ruleSignStr.split('&')[0]
                return ruleSign
            }
            else {
                return ruleSignStr
            }
        }
        else {
            return false
        }

    }

    exports.isDrawCouponLink = isDrawCouponLink;

    // 小程序事件处理
    function minAppEven(obj, arg, url, isAlipay) {
        obj.off('click');
        obj.on('click',function() {
            // console.log(arg)
            // 小程序物品详情
            if(arg) {
                if(isAlipay) {
                    my.navigateTo({
                        url: '/pages/shopping/goodsDetail/goodsDetail?goodsSn=' + arg
                    })
                }
                else {
                    wx.miniProgram.navigateTo({
                        url: '/pages/shopping/goodsDetail/goodsDetail?goodsSn=' + arg
                    });
                }

            }
            else if(url){
                wx.miniProgram.navigateTo({
                    url: url
                });
            }
            // 小程序首页
            else {
                if(isAlipay) {
                    my.switchTab({
                        url: '/pages/home/home'
                    })
                }
                else {
                    wx.miniProgram.switchTab({
                        url: '/pages/home/home'
                    });
                }

            }
        });
    }

    // 安卓绑定点击事件
    function AndroidGoods(obj,arg) {
        obj.off('click');
        obj.on('click',function() {
            android.goodsDetail(arg)
        })
    }

    // 安卓绑定点击返回首页
    function AndroidReHome(obj) {
        obj.off('click');
        obj.on('click',function() {
            android.toMainAcivity();
        })
    }


    function removeArrayChildren(arr, val) {
        var index = arr.indexOf(val);
        if (index > -1) {
            arr.splice(index, 1);
        }
    }
    exports.removeArrayChildren = removeArrayChildren;


    // 弹框获取焦点后 页面高度调整
    function setFocusBodyScrollTop(timer, fn) {
        var cnt = 0;
        var oBody = $('body');
        timer = setInterval(function() {
            if (cnt < 3) {
                cnt++;
            }
            else {
                clearInterval(timer);
                timer = null;

                return;
            }
            oBody[0].scrollTop =  oBody[0].scrollHeight;
            if(fn) fn();
        }, 300);
    }

    exports.setFocusBodyScrollTop = setFocusBodyScrollTop;


    function locationHref(href){
        $('body').append($('<a href="'+href+'"><span id="locationHrefId"><span><a>'));
        $('#locationHrefId').click();
    }
    exports.locationHref = locationHref;



    // 检测 安卓 ios 隐藏指定对象
    function  JudgeAppHide(ios, and, h5) {
        var u = navigator.userAgent;
        //var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
        var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端

        // 检测室安卓还是ios
        if(u.search('origin/sfddjapp') > 0) {
            if(isIOS) {
                if(ios) ios();
            }
            else {
                if(and) and();
            }
        }

        // 检测ddj
        else {
            if(h5) h5();
        }
    }
    exports.JudgeAppHide = JudgeAppHide;



    function isIphoneXsMinX() {
        return /iphone/gi.test(navigator.userAgent) && (screen.height == 812 && screen.width == 375)
    }
    exports.isIphoneXsMinX = isIphoneXsMinX;


    function isIphoneXRXSMax() {
        return /iphone/gi.test(navigator.userAgent) && (screen.height == 896 && screen.width == 414)
    }
    exports.isIphoneXRXSMax = isIphoneXRXSMax;

    /**
     * 判断是否是微信浏览器
     * @returns {Boolean}
     */
    function isWeiXin() {
        var ua = window.navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == 'micromessenger') {
            return true;
        } else {
            return false;
        }
    }
    exports.isWeiXin = isWeiXin;
    /**
     * 判断是否是支付宝浏览器
     * @returns {boolean}
     */
    function isAlipayClient() {
        var ua = window.navigator.userAgent.toLowerCase();
        if (ua.match(/AlipayClient/i) == 'alipayclient') {
            return true;
        } else {
            return false;
        }
    }
    exports.isAlipayClient = isAlipayClient;

    /**
     * 判断是否是QQ内置浏览器
     * @returns {boolean}
     */
    function isQQClient() {
        var ua = window.navigator.userAgent.toLowerCase();
        if (ua.match(/QQ/i) == 'qq') {
            return true;
        } else {
            return false;
        }
    }
    exports.isQQClient = isQQClient;

    //XSS 前端过滤
    function XssCheck(str,reg){
        return str ? str.replace(reg ||/[&<">'](?:(amp|lt|quot|gt|#39|nbsp|#\d+);)?/g,function (a, b) {
            if(b){
                return a;
            }else{
                return{
                    '<':'&lt;',
                    '&':'&amp;',
                    '"':'&quot;',
                    '>':'&gt;',
                    "'":'',
                }[a]
            }
        }): '';
    }
    exports.XssCheck = XssCheck;

    /*
    * 判断用户是否安装app,已安装就跳app,未安装就正常跳h5页面
    * 因可能有安卓跳A页面，ios跳B页面的情况，所以两种终端的url分开写
    * androidUrl, iosUrl是跳的指定页面  比如'https://m.sfddj.com/coupon/toCouponCenter'
    * 如果没有指定页面(首页)就不填写或者填写空'' 如isHasApp('','',function(){})或者isHasApp()
    * */
    function isHasApp(androidUrl, iosUrl, fn) {
        var u = navigator.userAgent;
        var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //android终端或者uc浏览器
        var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
        if(u.search('origin/sfddjapp') == -1) {
            if (isAndroid) {              // 在安卓的终端
                var HrefUrl = '';
                if (androidUrl && androidUrl != undefined && androidUrl != '') {
                    HrefUrl = 'ddjapp://cn.dankal.sf/webpage?url=' + androidUrl;
                } else {
                    HrefUrl = 'ddjapp://cn.dankal.sf/android';
                }
                // window.location.href = HrefUrl;
                locationHref(HrefUrl);
                setTimeout(function () {
                    if (fn) fn();
                    // alert('andbb');
                    // alert('正常打开安卓')
                }, 2000)
            }
            else if (isiOS) {            // 在ios的终端
                var HrefUrl = '';
                if (iosUrl && iosUrl != undefined && iosUrl != '') {
                    HrefUrl = 'ddjapk://weburl?url=' + iosUrl;
                } else {
                    HrefUrl = 'ddjapk://cn.dankal.sf';
                }
                window.location.href = HrefUrl;
                setTimeout(function () {
                    if (fn) fn();
                    // alert('ioscc');
                    // alert('正常打开ios')
                }, 2000)
            }
        }
        else{
            // 在app终端
            // alert('app')
        }

    }
    exports.isHasApp = isHasApp;

});


